import {PlusOutlined} from '@ant-design/icons';
import {Button, message, Input, Drawer} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {useIntl, FormattedMessage} from 'umi';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable, {EditableProTable} from '@ant-design/pro-table';
import ReactJson from 'react-json-view'

import {ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import {createDo} from '@/services/doa/repo'
import ProForm from '@ant-design/pro-form'
import ProCard from "@ant-design/pro-card";

//TODO 支持更新metadata

//{"id":"","type":"0.TYPE/DO","attributes":{"title":"sam发推：什么时候由媒体来宣布下任总统了？","source":"环球网","publishTime":"2020-11-09 06:46","url":"https://world.huanqiu.com/article/40cnJsElNVt","metadata":{"标题":"柳熠发推：什么时候由媒体来宣布下任总统了？","来源":"环球网","分类":"新闻"}},"elements":[{"id":"test","length":"3","dataString":"aaa","attributes":{"attr":"bbb"}}]}
const MetaDataManagement = () => {

  const meta = [
    {"key": "title", "desc": "数字对象名称（title)"},
    {"key": "description", "desc": "数字对象描述（description)"},
    {"key": "type", "desc": "数字对象分类（type)"},
    {"key": "date", "desc": "创建时间（date)"},
    {"key": "format", "desc": "格式（format)"},
    {"key": "language", "desc": "语言（language)"},
    {"key": "source", "desc": "来源（source）"},
    {"key": "topic", "desc": "主题（topic)"},
    {"key": "coverage", "desc": "范围（coverage)"}
  ]


  const info = (msg) => {
    message.info(msg);
  };


  const defaultMetaDo = meta.map((value, index) => {
    return {
      id: index.toString(),
      key: value.key,
      desc: value.desc,
      value: "",
    }
  })



  const updateMetadata = ()=>{
    const metadata ={}
    for(const item in dataSource){
      metadata[dataSource[item]?.key] = dataSource[item]?.value
    }
    const doNew =  JSON.parse(JSON.stringify(doInfo))
    if(doNew.attributes == null){
      doNew.attributes = {}
    }
    doNew["attributes"]["metadata"] = metadata
  }


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const intl = useIntl();

  const [editableKeys, setEditableRowKeys] = useState(() =>
    defaultMetaDo.map((item) => item.id),
  );

  const [dataSource, setDataSource] = useState(() => defaultMetaDo);

  const columns = [
    {
      title: '元数据字段键',
      key: 'key',
      dataIndex: 'key',
      editable: (text, record, index) => {
        return index > 8;
      },
    },
    {
      title: '元数据字段描述',
      dataIndex: 'desc',
      width: '30%',
      editable: (text, record, index) => {
        return index > 8;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            whitespace: true,
            message: '此项是必填项',
          }
        ],
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
      ],
    },
  ];


  return (
    <PageContainer>
      <ProCard>
        <EditableProTable
          headerTitle="编辑元数据标准"
          columns={columns}
          rowKey="id"
          value={dataSource}
          onChange={setDataSource}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            record: () => ({
              id: "" + (dataSource.length + 1),
            }),
          }}
          toolBarRender={() => {
            return [
              <Button
                type="primary"
                key="save"
                onClick={() => {
                  // dataSource 就是当前数据，可以调用 api 将其保存
                  console.log(dataSource);
                  updateMetadata()
                }}
              >
                保存数据
              </Button>,
            ];
          }}
          editable={{
            type: 'multiple',
            editableKeys,
            actionRender: (row, config, defaultDoms) => {
              return [defaultDoms.delete];
            },
            onValuesChange: (record, recordList) => {
              console.log(record)
              console.log(recordList)
              setDataSource(recordList);
            },
            onChange: setEditableRowKeys,
          }}
        />
      </ProCard>

    </PageContainer>
  );
};

export default MetaDataManagement;

